package com.nys.cqhttp.message.factory.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.nys.cqhttp.model.Massage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSONObject;
import com.nys.cqhttp.constant.CommonConstant;
import com.nys.cqhttp.message.factory.IMessageHandler;

import com.nys.cqhttp.param.Context;
import com.nys.cqhttp.util.SpringContextUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * JingRiTouTiaoMessageHandler
 *
 * @author nysheng
 * @version 1.0.0
 * @description 今日头条
 * @date 2021/12/28 19:53
 */
@Slf4j
public class JingRiTouTiaoMessageHandler implements IMessageHandler {

    @Override
    public List<String> listHandler(Massage messagePojo, Context context) {
        List<String> resultList = new ArrayList<>();
        List<JSONObject> list = getData(messagePojo, context);
        list.forEach(jsonObject -> resultList.add(String.valueOf(jsonObject.get("abstract"))));
        return resultList;
    }

    @Override
    public String handler(Massage messagePojo, Context context) {
        List<JSONObject> list = getData(messagePojo, context);
        if(context.getIndex()<=0 || context.getIndex()>list.size()){
            context.setIndex(1);
        }
        JSONObject jsonObject = list.get(context.getIndex()-1);
        String title = String.valueOf(jsonObject.get("abstract"));
        String url = String.valueOf(jsonObject.get("display_url"));
        return String.format(CommonConstant.CQ_SAHARE, url, title);
    }

    private List<JSONObject> getData(Massage messagePojo, Context context){
        List<JSONObject> resultList = new ArrayList<>();
        RestTemplate restTemplate = SpringContextUtil.getBean("restTemplate");
        try {
            Map<String ,Object> map = restTemplate.getForEntity(messagePojo.getValue(), Map.class).getBody();
            if(StringUtils.equals("success", String.valueOf(map.get("message")))){
                StringBuilder stringBuilder = new StringBuilder();
                List<Map<String, String>> dataList = (List<Map<String, String>>)map.get("data");
                dataList.forEach(data -> {
                    String content = data.get("content");
                    JSONObject jsonObject = JSONObject.parseObject(content);
                    resultList.add(jsonObject);
                });
            }
        }catch (Exception e){}
        return resultList;
    }
}
